package com.lkc.interceptor;

import com.lkc.domain.entity.User;
import com.lkc.enums.AppHttpCodeEnum;
import com.lkc.exception.SystemException;
import com.lkc.mapper.UserMapper;
import com.lkc.utils.JwtUtil;
import com.lkc.utils.security.LoginUser;
import io.jsonwebtoken.Claims;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.servlet.HandlerInterceptor;
import org.yaml.snakeyaml.events.Event;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Objects;

@Slf4j
@Component
public class LoginInterceptor implements HandlerInterceptor {

    @Resource
    private UserMapper userMapper;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {

        log.error(request.getMethod());
        String token = request.getHeader("token");
        //判断token是否为空，如果为空也代表未登录 提醒重新登录（401）
        if (!StringUtils.hasText(token)) {
            throw new SystemException(AppHttpCodeEnum.NEED_LOGIN);
        }
        //解析token看看是否成功
        Long id = -1L;
        try {
            Claims claims = JwtUtil.parseJWT(token);
            id = Long.valueOf(claims.getSubject());
        } catch (Exception e) {
            e.printStackTrace();
            throw new SystemException(AppHttpCodeEnum.LOGIN_ILLEGAL);
        }
        //通过id获取到用户
        User user = userMapper.selectById(id);
        if (Objects.isNull(user)) {
            throw new SystemException(AppHttpCodeEnum.LOGIN_ILLEGAL);
        }
        //将用户存放在LoginUser里面
        LoginUser.setUser(user);

        return true;
    }
}